<!DOCTYPE html>
<html height100 xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" lang="zh">
<head>
    <meta th:replace="authority/dynamic/common/edit/head"/>
</head>

<body class="childrenBody exclude-table-style" padding10>
<form class="layui-form layui-form-pane" lay-filter="form-time-task" onsubmit="return false;">
    <input type="hidden" name="id" value="">
    <div class="layui-form-item">
        <label for="D_name" class="layui-form-label"><span class="x-red">*</span>名称</label>
        <div class="layui-input-block">
            <input type="text" class="layui-input" id="D_name" name="name" lay-verify="required"
                   placeholder="名称" autocomplete="off" value="">
        </div>
        <div class="my-notes">
            <div class="layui-elip layui-text content">
                任务名称，简要描述用途
            </div>
        </div>
    </div>
    <div class="layui-row layui-col-space15 layui-form-item">
        <div class="layui-col-sm6">
            <label for="D_cronId" class="layui-form-label"><span class="x-red">*</span>CRON语句</label>
            <div class="layui-input-block">
                <input type="text" class="layui-input" id="D_cronId" lay-verify="required" name="cronId"
                       placeholder="请选择CRON语句" autocomplete="off" readonly>
            </div>
            <div class="my-notes">
                <div class="layui-elip layui-text content">
                    CRON语句是给计划任务的执行条件约定
                </div>
            </div>
        </div>
        <div class="layui-col-sm6">
            <label for="D_executionStrategy" class="layui-form-label"><span class="x-red">*</span>执行策略</label>
            <div class="layui-input-block">
                <select name="executionStrategy" id="D_executionStrategy" type="text" lay-verify="required">
                    <option value="0">多实例执行</option>
                    <option value="1">单实列执行(等待)</option>
                    <option value="2">单实列执行(跳过当前)</option>
                </select>
            </div>
            <div class="my-notes">
                <div class="layui-elip layui-text content">
                    多实例执行：前一个任务未执行完时，后面的任务重新启动实例继续执行 <br>
                    单实列执行(等待)：前一个任务未执行完时，后面的任务等待前面的任务执行完后再执行 <br>
                    单实列执行(跳过当前)：前一个任务未执行完时，后面的任务就不在执行了
                </div>
            </div>
        </div>
    </div>
    <div class="layui-row layui-col-space15 layui-form-item">
        <div class="layui-col-sm6">
            <label for="D_sort" class="layui-form-label"><span class="x-red">*</span>排序号</label>
            <div class="layui-input-block">
                <input type="number" name="sort" id="D_sort" class="layui-input" lay-verify="required"
                       autocomplete="off">
            </div>
        </div>
        <div class="layui-col-sm6">
            <label for="D_taskType" class="layui-form-label"><span class="x-red">*</span>任务类型</label>
            <div class="layui-input-block">
                <select name="taskType" id="D_taskType" type="text" lay-verify="required" lay-filter="taskType">
                    <option value="">--请选择--</option>
                </select>
            </div>
            <div class="my-notes">
                <div class="layui-elip layui-text content" id="D_taskType_notes">
                    保存后的数据不能再修改类型，否则之前的任务将无法操作 <br>
                </div>
            </div>
        </div>
    </div>
    <div id="execute-content-container"></div>
    <div class="layui-row layui-form-item" pane>
        <label for="D_state" class="layui-form-label"><span class="x-red">*</span>默认启动</label>
        <div class="layui-input-block">
            <input type="checkbox" name="state" id="D_state" lay-skin="switch" lay-text="启动|不启动">
            <small style="margin-left: 25px;" class="layui-elip layui-text">启动：系统启动时/保存时会自动启动任务； 不启动：仅在手动启动时启动</small>
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">备注</label>
        <div class="layui-input-block">
            <textarea placeholder="请输入备注内容" class="layui-textarea"></textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <button class="layui-btn" style="float: right" id="my-submit" lay-filter="submit" lay-submit>保存信息</button>
    </div>
</form>
<!--执行dml的模板-->
<script type="text/html" id="execute_dml_template">
    <div class="layui-form-item">
        <label for="D_dmlId" class="layui-form-label"><span class="x-red">*</span>DML语句</label>
        <div class="layui-input-block">
            <input type="text" class="layui-input" id="D_dmlId" lay-verify="required" name="dmlId"
                   placeholder="请选择DML语句" autocomplete="off" readonly>
        </div>
        <div class="my-notes">
            <div class="layui-elip layui-text content">
                选择需要计划任务需要执行的DML语句
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <fieldset class="layui-elem-field">
            <legend>DML参数设置</legend>
            <div class="layui-field-box" id="execute_dml_params_container">
                <!--放置参数-->
                <p class="layui-text layui-elip zsa-execute-dml-params-notes">请选择dml</p>
            </div>
        </fieldset>
    </div>
</script>
<!--执行dml参数的模板-->
<script type="text/html" id="execute_dml_params_template">
    <div class="layui-form-item">
        <label class="layui-form-label" style="width: 160px;"><span class="x-red">*</span></label>
        <div class="layui-input-block" style="margin-left: 160px;">
            <input type="text" class="layui-input" lay-verify="required" name="" placeholder=""
                   autocomplete="off">
        </div>
    </div>
</script>
<script th:replace="authority/dynamic/common/edit/footer"></script>
<script>
    layui.use(['form', 'lutil', 'initPage', 'tableSelect'], function () {
        var form = layui.form,
            lutil = layui.lutil,
            tableSelect = layui.tableSelect,
            initPage = layui.initPage;
        var EXECUTE_DML_TEMPLATE_HTML = $('#execute_dml_template').html(),
            EXECUTE_DML_PARAMS_TEMPLATE_HTML = $('#execute_dml_params_template').html();
        initPage.render({successCallback: initPageSuccess})
            .addFunction(initTaskTypeData)
            .start();

        function initTaskTypeData(functionSuccess) {
            ajaxRequestByCsrf(content_path + "authority/dic/list.do", {parentId: "794E6DE044654C0A90247946F37BD3FA"}, function (res) {
                for (var i = 0; i < res.data.length; i++) {
                    $("#D_taskType").append('<option value="' + res.data[i]['id'] + '">' + res.data[i]['name'] + ' </option>');
                    $("#D_taskType_notes").append(res.data[i]['remark']).append("<br>");
                }
                form.render('select', 'form-time-task');
            }, null, function () {
                functionSuccess();
            });
        }

        function initPageSuccess() {
            if ("[[${id}]]" !== '') {
                var loading = layer.load(2, {shade: [0.3, '#eee']});
                ajaxRequestByCsrf(content_path + 'authority/timed_task/detail/[[${id}]].do', {}, function (res) {
                    // $("#D_taskType").attr("disabled", "disabled");
                    form.val("form-time-task", $.extend(res.data, {state: res.data['state'] === 1}));
                    $("#D_taskType + .layui-form-select dl dd.layui-this").click();
                    $("#D_taskType").attr("disabled", "disabled");
                    form.render('select', 'form-time-task');
                    $("#D_cronId").val(res.data.cronName + " （" + res.data.cronId + "）").attr('ts-selected', res.data['cronId']);
                    $("#D_dmlId").attr('ts-selected', res.data['dmlId']);
                    setDmlDetailed($("#D_dmlId"), {name: res.data['dmlName'], id: res.data['dmlId']});
                    if (res.data['dmlParams']) {
                        var dmlParams;
                        try {
                            dmlParams = JSON.parse(res.data['dmlParams']);
                        } catch (e) {
                        }
                        if (dmlParams)
                            $('#execute_dml_params_container input[type=text]').each(function (i, e) {
                                if (e === undefined) return true;
                                $(this).val(dmlParams[$(this).attr('param-name')]);
                            });
                    }
                }, null, function (res) {
                    layer.close(loading);
                });
            }
        }

        tableSelect.render({
            elem: '#D_cronId',	//定义输入框input对象 必填
            checkedKey: 'id', //表格的唯一建值，非常重要，影响到选中状态 必填
            searchKey: 'name',	//搜索输入框的name值 默认keyword
            searchPlaceholder: '模糊搜索 CRON语句名称',	//搜索输入框的提示文字 默认关键词搜索
            searchCallback: function (table, data) {
                var searchs = [];
                $.each(data.field, function (i, e) {
                    searchs.push({field: i, formula: '<->', value: e});
                });
                table.query({searchs: JSON.stringify(searchs)});
            },
            table: {	//定义表格参数，与LAYUI的TABLE模块一致，只是无需再定义表格elem
                url: content_path + 'authority/plat/dml/paging_query.do',
                where: {
                    dmlId: '774788B3E6E441EE8388B899B3D5C403',
                    selectType: 2,
                    applicationId: "[[${applicationId}]]"
                },
                headers: {'[[${_csrf.headerName}]]': '[[${_csrf.token}]]'},
                cols: [
                    [
                        {type: 'radio'},
                        {field: 'id', title: 'ID'},
                        {field: 'name', title: '语句名'},
                        {field: 'cron', title: 'cron语句'},
                        {field: 'modifyUserName', title: '修改人'}
                    ]
                ]
            },
            done: function (elem, data) {
                if (data.data.length > 0) {
                    $(elem).val(data.data[0].name + " （" + data.data[0].cron + "）");
                } else {
                    $(elem).val('');
                }
            }
        });

        form.on('select(taskType)', function (data) {
            switch (data.value) {
                case '':
                    break;
                case '88872D3129B14FC4AFB936615BBFF1F2':
                    $('#execute-content-container').html($(EXECUTE_DML_TEMPLATE_HTML));
                    tableSelect.render({
                        elem: '#D_dmlId',	//定义输入框input对象 必填
                        checkedKey: 'id', //表格的唯一建值，非常重要，影响到选中状态 必填
                        searchKey: 'name',	//搜索输入框的name值 默认keyword
                        searchPlaceholder: '模糊搜索 DML名',	//搜索输入框的提示文字 默认关键词搜索
                        searchCallback: function (table, data) {
                            var searchs = [];
                            $.each(data.field, function (i, e) {
                                searchs.push({field: i, formula: '<->', value: e});
                            });
                            table.query({searchs: JSON.stringify(searchs)});
                        },
                        table: {	//定义表格参数，与LAYUI的TABLE模块一致，只是无需再定义表格elem
                            url: content_path + 'authority/plat/dml/paging_query.do',
                            where: {dmlId: '44A1685ECA934184AC3B636BBFCF1944', selectType: 2},
                            headers: {'[[${_csrf.headerName}]]': '[[${_csrf.token}]]'},
                            cols: [
                                [
                                    {type: 'radio'},
                                    {field: 'id', title: 'ID'},
                                    {field: 'name', title: 'DML语句名'},
                                    {field: 'modifyUserName', title: '最后修改人'}
                                ]
                            ]
                        },
                        done: function (elem, data) {
                            var paramsContainer = $('#execute_dml_params_container');
                            if (data.data.length > 0) {
                                setDmlDetailed(elem, data.data[0]);
                            } else {
                                $(elem).val('');
                                paramsContainer.find('.layui-form-item,.zsa-execute-dml-params-not').remove();
                                paramsContainer.find('.zsa-execute-dml-params-notes').removeClass('layui-hide');
                            }
                        }
                    });
                    break;
                default:
                    lutil.error_alert("该类型尚未设置，请联系管理员");
            }
        });

        function setDmlDetailed(elem, data) {
            var paramsContainer = $('#execute_dml_params_container');
            $(elem).val(data.name + " （" + data.id + "）");
            paramsContainer.find('.zsa-execute-dml-params-notes').addClass('layui-hide');
            paramsContainer.find('.layui-form-item,.zsa-execute-dml-params-not').remove();
            var loading = layer.load(2, {shade: [0.3, '#eee']});
            ajaxRequestByCsrf(content_path + 'authority/plat/dml/paging_query.do',
                {
                    dmlId: 'ED519B15FAC648CCAAC114BE8289EBCF',
                    selectType: 2,
                    columnDmlId: data.id
                },
                function (res) {
                    if (res.data.length === 0)
                        paramsContainer.append('<p class="layui-text layui-elip zsa-execute-dml-params-not">该DML不需要设置参数</p>');
                    $.each(res.data, function (i, e) {
                        var paramElem = $(EXECUTE_DML_PARAMS_TEMPLATE_HTML);
                        paramElem.find(".layui-form-label").append(e['caption']);
                        paramElem.find("input[type=text]").attr('param-name', e['lable']);
                        paramsContainer.append(paramElem);
                    });
                }, null, function () {
                    layer.close(loading);
                }, {async: false});
        };

        form.on('submit(submit)', function (formData) {
            var dmlParams = undefined, dmlId = $(formData.form).find('input[name=dmlId]').attr('ts-selected');
            $('#execute_dml_params_container input[type=text]').each(function (i, e) {
                if (!dmlParams) dmlParams = {};
                if (e === undefined) return true;
                dmlParams[$(this).attr('param-name')] = $(this).val();
            });
            var loading = layer.load(2, {shade: [0.3, '#eee']});
            ajaxRequestByCsrf(content_path + 'authority/timed_task/save.do', $.extend(formData.field, {
                state: formData.field['state'] ? 1 : 0,
                cronId: $(formData.form).find('input[name=cronId]').attr('ts-selected'),
                dmlId: dmlId,
                dmlParams: dmlParams ? JSON.stringify(dmlParams) : undefined
            }), function (res) {
                lutil.success_msg(res.message);
                var index = window.name && parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                parent.layer.close(index);
            }, null, function (res) {
                layer.close(loading);
            });
            return false;
        });
    })
</script>
</body>
</html>